package com.study.ming.studydemo.thd;

import org.junit.Test;

public class WaiteDemo {
    private static Object locker = new Object();

    public static void main(String[] args) throws InterruptedException {
        final WaiteDemo waiteDemo = new WaiteDemo(); // 启动新线程，防止主线程被休眠
        new Thread() {
            public void run() {
                try {
                    waiteDemo.doWait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
        Thread.sleep(2000); // 此行本身没有意义，是为了确保 wait() 先执行再执行 notify()
        waiteDemo.doNotify();
        System.out.println("主线程结束");
    }

    private void doWait() throws InterruptedException {
        synchronized (locker) {
            System.out.println("wait start.");
            locker.wait();
            System.out.println("wait end.");
        }
    }

    private void doNotify() {
        synchronized (locker) {
            System.out.println("notify start.");
            locker.notify();
            System.out.println("notify end.");
        }
    }

    @Test
    public void sdfsadf() throws InterruptedException {
        final WaiteDemo waitDemo = new WaiteDemo();
        new Thread() {
            public void run() {
                synchronized (locker) {
                    try {
                        System.out.println("sleep start.");
                        Thread.sleep(5000);
                        System.out.println("sleep end.");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
        Thread.sleep(1000);
        waitDemo.doNotify();
    }
}
